package com.xuebusi.mina.client.config;

import com.xuebusi.mina.client.handler.ClientHandler;
import com.xuebusi.mina.common.socket.SocketDecoder;
import com.xuebusi.mina.common.socket.SocketEncoder;
import org.apache.mina.core.service.IoHandler;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketConnector;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetSocketAddress;

@Configuration
public class MinaConfig {

    @Value("${mina.port}")
    private int port;
    @Value("${mina.host}")
    private String host;

    @Bean
    public InetSocketAddress inetSocketAddress() {
        return new InetSocketAddress(host, port);
    }

    @Bean
    public IoHandler ioHandler() {
        return new ClientHandler();
    }

    @Bean
    public NioSocketConnector nioSocketConnector() {
        // 创建客户端连接器.
        NioSocketConnector connector = new NioSocketConnector();
        connector.getFilterChain().addLast("logger", new LoggingFilter());
        // 设置编码过滤器
        connector.getFilterChain().addLast("codec",
                new ProtocolCodecFilter(new SocketEncoder(), new SocketDecoder()));
        // 设置事件处理器
        connector.setHandler(ioHandler());
        return connector;
    }
}
